{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Paddle Quantum 入门手册\n",
    "\n",
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <a name=\"Overview\">总览</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这是一份简洁、实用的关于量子机器学习（Quantum Machine Learnig，QML）的介绍，面向读者包括但不限于物理、数学和计算机背景。本手册主要采用 Jupyter Notebook 的交互形式 (调用 Numpy, Matplotlib 等 Python 包以及飞桨 Paddlepaddle 深度学习框架来实现基于线性代数的量子运算和机器学习优化问题)。我们不仅提供了关于量子计算的一些基础教程同时还能手把手带你完成属于你自己的第一份量子机器学习算法。这并不是一份关于量子计算的百科全书，但我们涉及的案例经常出现在教科书中以及文献中。如果你想深入挖掘一些相关的基础知识，我们也提供了一些外部链接方便用户自己学习。\n",
    "\n",
    "量子计算是由量子力学与计算理论交叉形成的新型学科，本质上是通过量子力学的基本规律去操控信息单元量子比特（quantum bit, qubit）的新型计算模式。与经典计算模型相比，在许多特定的信息处理任务上量子计算被普遍认为具有更强大的信息处理优势。关于量子计算的介绍与入门知识可以参考 [1-2]，想要系统性地学习量子计算学科的读者请参阅 Nielsen & Chuang 编写的经典教材 [3]。近期，量子计算领域中一个热门的课题是如何有效地结合量子计算和人工智能两者的潜能。量子机器学习便是这样一门结合了量子计算与机器学习的交叉学科，一方面研究者们希望利用量子计算的信息处理优势去促进人工智能的发展，另一方面也存在可能性去利用现有的人工智能的技术突破量子计算的研发瓶颈。关于量子机器学习的入门资料可以参考 [4-6]。\n",
    "\n",
    "内容上，这份快速入门包括以下几个方面：\n",
    "\n",
    "- 量子计算和量子神经网络的基础知识介绍\n",
    "- 量桨（Paddle Quantum）的使用介绍\n",
    "- 飞桨（PaddlePaddle）优化器的使用教程\n",
    "- 具体的量子机器学习案例—— 变分量子本征求解器（VQE）\n",
    "\n",
    "最后修改于: 2021年3月2日 由量桨 Paddle Quantum 开发小组共同完成。\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <a name=\"Contents\">目录</a> \n",
    "\n",
    "<ul>\n",
    "    <li><a href=\"#Overview\">入门手册总览</a>\n",
    "    <li><a href=\"#Paddle\">安装</a>:\n",
    "         [<a href=\"#conda\">Conda 与环境配置</a>]\n",
    "        [<a href=\"#pq\">安装 Paddle Quantum包</a>]\n",
    "    <li><a href=\"#QC\">量子计算基础</a>:\n",
    "         [<a href=\"#qubit\">量子比特</a>]\n",
    "         [<a href=\"#gate\">量子门</a>]\n",
    "         [<a href=\"#measure\">测量</a>]\n",
    "         [<a href=\"#ex1\">示例和练习</a>]\n",
    "    <li><a href=\"#VA\">量子电路模板的搭建</a>: \n",
    "         [<a href=\"#QNN\">量子神经网络QNN</a>]\n",
    "         [<a href=\"#Ansatz\">内置电路模板</a>]\n",
    "    <li><a href=\"#Mode\">量桨的运算模式</a>: \n",
    "         [<a href=\"#vec\">波函数向量模式</a>]\n",
    "         [<a href=\"#density\">密度矩阵模式</a>]\n",
    "         [<a href=\"#Bell\">练习：贝尔态</a>]\n",
    "    <li><a href=\"#Op\">飞桨优化器的使用</a>: \n",
    "         [<a href=\"#GD\">简单案例</a>]\n",
    "         [<a href=\"#ex2\">应用与练习</a>]\n",
    "    <li><a href=\"#demo\">量子机器学习案例</a>: \n",
    "         [<a href=\"#VQE\">无监督学习 - VQE</a>]\n",
    "    <li><a href=\"#References\">参考文献</a> \n",
    "        \n",
    "</ul>\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <a name=\"Paddle\">安装教程</a>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"conda\">Conda 与 Python 环境安装</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们推荐使用 [Anaconda](https://www.anaconda.com/download) 作为 Python3 的开发环境，支持多种主流操作系统（Windows, MacOS, 以及 Linux）。Anaconda 本身提供 Scipy, Numpy, Matplotlib 等科学计算、作图包，最主要的是其自带 Python 开发环境的管理器 conda，可以用来安装或者更新主流 Python 包。这里我们提供一个例子来学习使用 conda 创建和管理环境：\n",
    "\n",
    "1. 首先进入命令行 (Terminal) 界面：Windows 用户可以通过 `Anaconda Prompt`/ Mac用户可以使用组合键 `command⌘ + 空格` 再输入 `Terminal`。\n",
    "1. 进入 Terminal 后输入 `conda create --name paddle_quantum_env python=3.7` 创建名为 `paddle_quantum_env` 的 Python3.7 环境。\n",
    "1. 在 Terminal 内通过 `conda env list` 查看已有的环境，然后通过 `conda activate paddle_quantum_env ` 进入我们刚建立的环境。\n",
    "1. 为了能正确运行 Jupyter Notebook 我们还需要安装 `conda install jupyter notebook` 或者 `pip install jupyter notebook`。安装完成之后，如果你想开启 Jupyter 只需要在Terminal内激活正确的环境然后输入 `jupyter notebook` 即可。\n",
    "\n",
    "\n",
    "关于 conda 更多的本地指令请参考 [官方教程](https://docs.conda.io/projects/conda/en/latest/user-guide/getting-started.html)。\n",
    "<span class=\"blue\"> 此外，你也可以通过使用 <a href=\"https://docs.anaconda.com/anaconda/navigator/\"> Anaconda Navigator</a> 开启 jupyter notebook。\n",
    "\n",
    "以下是这个教程中你需要使用的包:\n",
    "<ul>\n",
    "    <li>Numpy\n",
    "    <li>Paddlepaddle 2.0.1+\n",
    "    <li>Paddle Quantum 2.0.0+\n",
    "</ul>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"pq\">安装 Paddle和 Paddle Quantum</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接着我们安装 Paddle Quantum 包，用户可以直接通过 `pip install paddle-quantum` 完成安装。关于本地安装方式，用户可以通过 Terminal 界面使用 git指令 `git clone http://github.com/PaddlePaddle/quantum` 或者直接下载 `zip` 压缩包，然后找到对应本地文件的路径输入 `cd quantum` 和 `pip install -e .` 完成安装。接着在 Terminal 界面输入`pip list`查看是否在正确的环境中安装完成。关于 git的使用和安装，请参考这篇 [教程](https://git-scm.com/book/zh/v2/%E8%B5%B7%E6%AD%A5-%E5%AE%89%E8%A3%85-Git)。此外，如果你需要更多的关于安装 Paddle Quantum 的帮助，可以参考我们的 [Github链接](https://github.com/PaddlePaddle/Quantum) 或者通过 Github Issues联系我们。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-30T09:18:51.118039Z",
     "start_time": "2021-04-30T09:18:47.681144Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import paddle\n",
    "from paddle import matmul, transpose, trace\n",
    "from paddle_quantum.circuit import UAnsatz\n",
    "from paddle_quantum.utils import dagger, random_pauli_str_generator, pauli_str_to_matrix\n",
    "from paddle_quantum.state import vec, vec_random, density_op, density_op_random"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以上的几个代码块没有任何报错的话，恭喜你！接着就可以顺利运行全部的教程了！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>[回到 <a href=\"#Contents\">目录</a>]</p>\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <a name=\"QC\">量子计算基础</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "量子计算（Quantum Computing, QC）是利用量子物理中特有的现象（量子叠加态、量子相干性和量子纠缠等）来设计相应的量子算法以解决 （物理、化学、计算机等领域）特定的任务。现有的量子计算有存在几种模型，例如基于绝热定理的绝热量子计算模型（Adiabatic Quantum Computation, AQC）以及基于测量的量子计算模型（Measurement-Based Quantum Computation, MBQC）等等。在本介绍中，我们主要讨论目前影响力最大、使用最广泛的量子电路（Quantum Circuit）模型。在量子电路的框架下，运算最基本的组成单元是量子比特（qubit）。这与经典计算机中比特（bit）的概念很相似。经典比特只能处于0和1两种状态中的某一种（物理图景上可以对应晶体管的高低电位）。与之不同的是，量子比特不仅可以处于两个状态 $|0\\rangle$ 还有 $|1\\rangle$ 还可以处于两者的叠加态（稍后我们来具体讲解下这一概念）。在量子电路模型中，我们通过由一系列量子逻辑门构成的量子电路来操控这些量子比特的状态从而完成计算任务。逻辑门运算的基本理论是线性代数，在此我们假定读者已经具备一定的线性代数基础。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"qubit\">什么是量子比特？</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数学表示\n",
    "\n",
    "在量子力学中，一个二能级系统微观粒子（qubit）的量子态（quantum state）可以表示为由两个正规正交基线性组合得到的向量，这些基向量一般可以写为\n",
    "\n",
    "$$\n",
    "|0\\rangle := \\begin{bmatrix} 1 \\\\ 0 \\end{bmatrix}, \\quad |1\\rangle := \\begin{bmatrix} 0 \\\\ 1 \\end{bmatrix}.\n",
    "\\tag{1}\n",
    "$$\n",
    "\n",
    "这里向量的表示方法采用了量子物理上传统的狄拉克表示（bra-ket）。这两个单位正交向量 $\\{|0\\rangle, |1\\rangle \\}$ 一般被称为**计算基**（computational basis）。物理图景中我们可以认为 $|0\\rangle$ 和 $|1\\rangle$ 分别对应一个原子的能量基态和激发态或者其他一些二分类状态。 一个量子比特所有可能的态可以看作是二维希尔伯特空间中所有的归一化向量，这个希尔伯特空间的一组正规正交基正是 $\\{|0\\rangle, |1\\rangle \\}$。更多的量子比特系统也同样可以由高维度的希尔伯特空间中的的单位向量表示，而这个高维希尔伯特空间的正交基就是 $\\{|0\\rangle, |1\\rangle \\}$ 的张量积。比如说，一个两量子比特（2-qubit）系统可以被一个4维的希尔伯特空间里的单位复数向量表示，而这个希尔伯特空间的正规正交基是\n",
    "\n",
    "$$\n",
    "\\left\\{\n",
    "|00\\rangle = |0\\rangle\\otimes |0\\rangle := \\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix}, \\quad \n",
    "|01\\rangle = |0\\rangle\\otimes |1\\rangle := \\begin{bmatrix} 0 \\\\ 1 \\\\ 0 \\\\ 0 \\end{bmatrix}, \\quad\n",
    "|10\\rangle = |1\\rangle\\otimes |0\\rangle := \\begin{bmatrix} 0 \\\\ 0 \\\\ 1 \\\\ 0 \\end{bmatrix}, \\quad\n",
    "|11\\rangle = |1\\rangle\\otimes |0\\rangle := \\begin{bmatrix} 0 \\\\ 0 \\\\ 0 \\\\ 1 \\end{bmatrix}\n",
    "\\right\\}.\n",
    "\\tag{2}\n",
    "$$\n",
    "\n",
    "我们默认最左边的位置代表第一个量子比特，依此类推。其中符号 $\\otimes$ 是张量积运算。其工作原理大概如下：给定两个矩阵 $A_{m\\times n}$ 还有 $B_{p \\times q}$，那么 $A,B$ 的张量积为\n",
    "\n",
    "$$\n",
    "A \\otimes B = \n",
    "\\begin{bmatrix}\n",
    "a_{11}B & \\cdots & a_{1 n}B\\\\\n",
    "\\vdots  & \\ddots & \\vdots \\\\\n",
    "a_{m1}B & \\cdots & a_{m n}B\n",
    "\\end{bmatrix}_{(mp)\\times (nq)}\n",
    "\\tag{3}\n",
    "$$\n",
    "\n",
    "一个单量子比特所处的任意量子态 $|\\psi\\rangle$ 可以写成基向量 $|0\\rangle$ 和 $|1\\rangle$ 的线性叠加，也就是说，它可以被描述成一个 $|0\\rangle$ 和 $|1\\rangle$ 的线性组合：\n",
    "\n",
    "$$\n",
    "|\\psi\\rangle = \\alpha |0\\rangle  + \\beta |1\\rangle\n",
    ":= \\begin{bmatrix} \\alpha \\\\ \\beta \\end{bmatrix}.\n",
    "\\tag{4}\n",
    "$$\n",
    "\n",
    "其中 $\\alpha$ 和 $\\beta$ 可以是**复数**，他们表示概率振幅。这意味着当我们测量这个量子比特时，根据波恩法则，测量得到量子比特处于 $|0\\rangle$ 状态的概率是 $|\\alpha|^2$；而测量得到 $|1\\rangle$ 的概率是 $|\\beta|^2$。由于概率相加等于 1，我们必须要加入如下的限制条件：$|\\alpha|^2 + |\\beta|^2 = 1$。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  布洛赫球面表示\n",
    "\n",
    "我们用一个球面上的点来表示一个量子比特可能处于的量子态，这个球面被称为**布洛赫球面**（Bloch Sphere），（见图1）\n",
    "\n",
    "$$\n",
    "|\\psi\\rangle = \\alpha |0\\rangle  + \\beta |1\\rangle  \n",
    "= \\cos\\bigg(\\frac{\\theta}{2}\\bigg) |0\\rangle +  e^{i\\varphi}\\sin\\bigg(\\frac{\\theta}{2}\\bigg) |1\\rangle.\n",
    "\\tag{5}\n",
    "$$\n",
    "\n",
    "**注意**：多个量子系统的状态就无法用布洛赫球面来表示。如果是一个经典比特的话，那么它只有两个状态0和1，也就是布洛赫球面的北极和南极。这两个位置恰好对应着 $|0\\rangle$ 和 $|1\\rangle$。**而一个量子比特不光可以处于两极，它可以在球面上任意一点，这样一种叠加的状态是经典比特做不到的**。举例来说，量子态 $\\frac{1}{\\sqrt{2}}\\big(|0\\rangle + i|1\\rangle\\big)$就处于球面赤道和 $y$-正半轴的交界处。\n",
    "\n",
    "<img src=\"figures/intro-fig-bloch.png\" width=\"250\" >\n",
    "\n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;  \n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;\n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;\n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;\n",
    "&emsp;&emsp;\n",
    "**图 1.** \n",
    "单量子比特的布洛赫球面表示. [[图片来源]](https://en.wikipedia.org/wiki/Qubit)\n",
    "\n",
    "下面的内容面向对量子计算更熟悉的读者。如果你阅读这段感到困难，不用担心，您可以选择略过这一节，这不会对理解接下的内容产生影响。由于量子比特之间的交互以及去相干问题 (Decoherence)，因此，对于一个具有多量子比特的系统来说，它的单量子比特子系统将不再处于纯态 (pure state)，而是演变成混合态 (mixed state)。混合态可以看成不同纯态的按照一定概率的混合。 **单比特的混合态可以看成是布洛赫球内部的点，而不是存在于球表面**。通常来说，混合态需要用到量子力学的密度矩阵形式来描述，比如以下量子态分别有 $1/2$ 的概率处于 $|0\\rangle$ 或 $|1\\rangle$ 态，\n",
    "\n",
    "$$\n",
    "\\rho_{\\text{mixed}} = \\sum_i P_i |\\psi_i\\rangle\\langle\\psi_i| = \\frac{1}{2} |0\\rangle\\langle0| + \\frac{1}{2} |1\\rangle\\langle1| := \\frac{1}{2}  \\begin{bmatrix} 1 \\\\ 0\\end{bmatrix} \\begin{bmatrix} 1 & 0 \\end{bmatrix} +  \\frac{1}{2}  \\begin{bmatrix} 0 \\\\ 1\\end{bmatrix} \\begin{bmatrix} 0 & 1 \\end{bmatrix} = \\frac{1}{2} \\begin{bmatrix} 1 & 0\\\\ 0 & 1 \\end{bmatrix}.\n",
    "\\tag{6}\n",
    "$$\n",
    "\n",
    "其中行向量（bra）$\\langle0|$ 是列向量 （ket）$|0\\rangle$ 的复共轭转置。\n",
    "\n",
    "**注：** 如需更多信息，可参考维基百科 [链接](https://en.wikipedia.org/wiki/Qubit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"gate\">什么是量子逻辑门？</a>\n",
    "\n",
    "在经典计算机中，我们可以在经典比特上施加基本的逻辑运算（非门 NOT, 与非门 NAND, 异或门 XOR, 与门 AND, 或门 OR）并组合成更复杂的运算。而量子计算则有完全不同的一套逻辑运算，它们被称为量子门 (quantum gate)。我们并不能在一个量子计算机上编译现有的C++程序。因为**经典计算机和量子计算机有不同的逻辑门构造，所以量子算法是需要利用这些量子门的特殊性来构造的**。量子门在数学上可以被表示成酉矩阵（unitary matrix）。酉矩阵操作可以保证向量的长度不变，这是个很好的性质。不然我们对一个纯态量子比特进行操作，会让它劣化成混合态导致其无法接着很好地使用。酉矩阵定义为：\n",
    "\n",
    "$$\n",
    "U^{\\dagger}U = UU^{\\dagger} = I, \n",
    "\\quad \\text{并且} \\quad \n",
    "\\Vert |\\psi\\rangle \\Vert  = \\Vert U|\\psi\\rangle\\Vert = 1.\n",
    "\\tag{7}\n",
    "$$\n",
    "\n",
    "其中 $U^{\\dagger}$ 是 $U$ 的共轭转置，$I$ 表示单位矩阵。但是酉矩阵作为量子门的物理意义是什么？这意味着**所有的量子门都必须是可逆的**。对于任何一个量子门运算，都可以找到一个与其对应的反向运算。除此之外，酉矩阵必须是个方阵。因为量子门的输入和输出要求有同样数量的量子比特。一个作用在 $n$ 量子比特的量子门可以写成一个 $2^n \\times 2^n$ 的酉矩阵。最常见的（也是物理上最容易实现的）量子门作用在一个或两个量子比特上，就像经典逻辑门那样。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 单量子比特门\n",
    "\n",
    "接下来，我们介绍在量子计算中非常重要的单量子比特门，包括泡利矩阵 $\\{X, Y, Z\\}$、单比特旋转门 $\\{R_x, R_y, R_z\\}$ 和 Hadamard 门 $H$。其中 **非门（NOT gate）** 对于经典或量子计算都很重要，酉矩阵表示为：\n",
    "\n",
    "$$\n",
    "X := \\begin{bmatrix} 0 &1 \\\\ 1 &0 \\end{bmatrix},\n",
    "\\tag{8}\n",
    "$$\n",
    "\n",
    "这个量子门（酉矩阵）作用在单量子比特（一个复向量）上本质上的运算是**矩阵乘以向量**：\n",
    "\n",
    "$$\n",
    "X |0\\rangle := \\begin{bmatrix} 0 &1 \\\\ 1 &0 \\end{bmatrix} \\begin{bmatrix} 1 \\\\0 \\end{bmatrix} \n",
    "=\\begin{bmatrix} 0 \\\\1 \\end{bmatrix} = |1\\rangle, \n",
    "\\quad \n",
    "X |1\\rangle := \\begin{bmatrix} 0 &1 \\\\ 1 &0 \\end{bmatrix} \\begin{bmatrix} 0 \\\\1 \\end{bmatrix} \n",
    "=\\begin{bmatrix} 1 \\\\0 \\end{bmatrix}=|0\\rangle.\n",
    "\\tag{9}\n",
    "$$\n",
    "\n",
    "回忆起前面的布洛赫球面表示，这个矩阵 $X$ 作用在一个量子比特（布洛赫球面上的一点）就相当于**关于布洛赫球的 $x$ 轴旋转角度 $\\pi$**。这就是为什么 $X$ 可以表示成 $R_x(\\pi)$（相差全局相位 $e^{-i\\pi/2} = -i$）。其他两个泡利矩阵 $Y$ 和 $Z$ 在这一点上也非常相似（代表绕 $y$ 和 $z$ 轴旋转 $\\pi$ 角度 ）：\n",
    "\n",
    "$$\n",
    "Y := \\begin{bmatrix} 0 &-i \\\\ i &0 \\end{bmatrix},\n",
    "\\quad \n",
    "Z := \\begin{bmatrix} 1 &0 \\\\ 0 &-1 \\end{bmatrix}.\n",
    "\\tag{10}\n",
    "$$\n",
    "\n",
    "一般来说，任何一个在布洛赫球关于相应的轴旋转 $\\theta$ 角度的量子门可以表示为：\n",
    "\n",
    "$$\n",
    "R_x(\\theta) := \n",
    "\\begin{bmatrix} \n",
    "\\cos \\frac{\\theta}{2} &-i\\sin \\frac{\\theta}{2} \\\\ \n",
    "-i\\sin \\frac{\\theta}{2} &\\cos \\frac{\\theta}{2} \n",
    "\\end{bmatrix}\n",
    ",\\quad \n",
    "R_y(\\theta) := \n",
    "\\begin{bmatrix}\n",
    "\\cos \\frac{\\theta}{2} &-\\sin \\frac{\\theta}{2} \\\\ \n",
    "\\sin \\frac{\\theta}{2} &\\cos \\frac{\\theta}{2} \n",
    "\\end{bmatrix}\n",
    ",\\quad \n",
    "R_z(\\theta) := \n",
    "\\begin{bmatrix}\n",
    "e^{-i\\frac{\\theta}{2}} & 0 \\\\ \n",
    "0 & e^{i\\frac{\\theta}{2}}\n",
    "\\end{bmatrix}.\n",
    "\\tag{11}\n",
    "$$\n",
    "\n",
    "除了旋转门之外，最重要的单比特门就是 Hadamard 门了。对应的布洛赫球面解释是两个旋转组成的，先是按 $z$ 轴旋转 $\\pi$，然后按 $y$ 轴旋转 $\\pi/2$。它的矩阵表示是\n",
    "\n",
    "$$\n",
    "H := \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1 &1 \\\\ 1 &-1 \\end{bmatrix}.\n",
    "\\tag{12}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 两比特量子门\n",
    "\n",
    "从单量子比特门我们可以拓展到两量子比特门。有两种拓展方式，第一种是只挑选出一个量子比特，在上面施加单量子比特门，其他的量子比特则不进行任何操作。有的时候，会见到如下图所示的量子电路："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"figures/intro-fig-hadamard.png\" width=\"600\" >\n",
    "\n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;  \n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;\n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;\n",
    "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;\n",
    "**图 2.** \n",
    "两量子比特逻辑运算的电路表示和解读. [[图片来源]](https://en.wikipedia.org/wiki/Quantum_logic_gate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "作用在两量子比特上的量子门可以表示成一个 $4\\times4$ 酉矩阵：\n",
    "\n",
    "$$\n",
    "U = H \\otimes I \n",
    "= \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 &1 \\\\ 1 &-1 \\end{bmatrix} \n",
    "\\otimes \\begin{bmatrix} 1 &0 \\\\ 0 &1 \\end{bmatrix} \n",
    "= \\frac{1}{\\sqrt{2}} \\,\n",
    "\\begin{bmatrix}\n",
    "1 &0 &1 &0  \\\\ \n",
    "0 &1 &0 &1  \\\\\n",
    "1 &0 &-1 &0 \\\\\n",
    "0 &1 &0 &-1 \n",
    "\\end{bmatrix}\n",
    "\\tag{13}\n",
    "$$\n",
    "\n",
    "另一种拓展方式是将逻辑门直接作用在两个量子比特上。比如受控非门 $\\text{CNOT}$，这个门会使得一个量子比特的状态影响到另一个量子比特的状态\n",
    "\n",
    "$$\n",
    "\\text{CNOT} := \n",
    "\\begin{bmatrix} \n",
    "1 &0 &0 &0 \\\\ \n",
    "0 &1 &0 &0 \\\\\n",
    "0 &0 &0 &1 \\\\\n",
    "0 &0 &1 &0 \n",
    "\\end{bmatrix}.\n",
    "\\tag{14}\n",
    "$$\n",
    "\n",
    "我们观察一下它作用在不同的初始量子态上：\n",
    "\n",
    "$$\n",
    "\\text{CNOT} |00\\rangle = |00\\rangle, \\quad\n",
    "\\text{CNOT} |01\\rangle = |01\\rangle, \\quad\n",
    "\\text{CNOT} |10\\rangle = |11\\rangle, \\quad\n",
    "\\text{CNOT} |11\\rangle = |10\\rangle.\n",
    "\\tag{15}\n",
    "$$\n",
    "\n",
    "也就是说，当第一个量子比特处于 $|1\\rangle$ 状态时，$\\text{CNOT}$ 会在第二个量子比特上施加 $X$ 门，如果第一个量子比特处于 $|0\\rangle$ 状态，那么第二个量子比特则不受任何影响。这也是为什么 $\\text{CNOT}$ 会被称为受控非门。下面是一些常见的量子门及它们的矩阵表示，**这些量子门都可以在量桨内被调用**。\n",
    "\n",
    "![intro-fig-gates](./figures/intro-fig-gates.png \"**图 3.** 常见的量子门. [[图片来源]](https://en.wikipedia.org/wiki/Quantum_logic_gate)\")\n",
    "\n",
    "**注**：更多信息可见如下维基百科 [链接](https://en.wikipedia.org/wiki/Quantum_logic_gate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  <a name=\"measure\">什么是量子力学中的测量？</a>\n",
    "\n",
    "对于一个两分类的量子态，比如电子的自旋（Spin），我们规定该电子自旋向上 $\\uparrow$ 时记为 $|0\\rangle$ 态，自旋向下 $\\downarrow$ 时记为 $|1\\rangle$ 态。神奇的是，电子等微观粒子在被观测之前可以同时处于自旋向上和自旋向下的叠加态 $|\\psi\\rangle =\\alpha |0\\rangle  + \\beta |1\\rangle$。那么这个叠加态到底指的是什么呢？答案很简单，我们可以去测量一下这个处于\"叠加态\"的电子。值得注意的是，量子力学中的测量通常指的是一个统计结果而不是单次测量。这是由于测量本身的特性会使得观察后的量子态塌缩。就拿我们前面提到的处于 $|\\psi\\rangle$ 态的这个电子来举例，如果我们测量这一个电子的自旋，我们会有 $|\\alpha|^2$ 的概率观测到自旋向上并且观测后量子态塌缩成 $ |0\\rangle$。同样的，我们也有 $|\\beta|^2$ 的概率测量得到自旋向下$|1\\rangle$。那么想要精确的得到 $\\alpha$ 的数值，一次实验显然是不够的。我们需要拜托物理学家朋友准备了好多好多处于叠加态 $\\alpha |0\\rangle  + \\beta |1\\rangle$ 的电子，把每一个的自旋都测量再统计频率。测量在量子力学中地位比较特殊，如果读者觉得难理解。请参阅 [维基百科-量子力学中的测量](https://en.wikipedia.org/wiki/Measurement_in_quantum_mechanics#:~:text=In%20quantum%20physics%2C%20a%20measurement,makes%20are%20in%20general%20probabilistic.) 获取更多知识。\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##    <a name=\"ex1\">示例以及练习</a>\n",
    "\n",
    "### 示例: 用 Paddle Quantum 创建 $X$ 门\n",
    "\n",
    "**注意:** 所有的单比特旋转门都按如下规定建立：\n",
    "\n",
    "$$\n",
    "R_x(\\theta) := \n",
    "\\begin{bmatrix} \n",
    "\\cos \\frac{\\theta}{2} &-i\\sin \\frac{\\theta}{2} \\\\ \n",
    "-i\\sin \\frac{\\theta}{2} &\\cos \\frac{\\theta}{2} \n",
    "\\end{bmatrix}\n",
    ",\\quad \n",
    "R_y(\\theta) := \n",
    "\\begin{bmatrix}\n",
    "\\cos \\frac{\\theta}{2} &-\\sin \\frac{\\theta}{2} \\\\ \n",
    "\\sin \\frac{\\theta}{2} &\\cos \\frac{\\theta}{2} \n",
    "\\end{bmatrix}\n",
    ",\\quad \n",
    "R_z(\\theta) := \n",
    "\\begin{bmatrix}\n",
    "e^{-i\\frac{\\theta}{2}} & 0 \\\\ \n",
    "0 & e^{i\\frac{\\theta}{2}}\n",
    "\\end{bmatrix}.\n",
    "\\tag{16}\n",
    "$$\n",
    "\n",
    "因此，我们不难看出 $X$ 门可以表示为 $R_x(\\pi)$。以下是代码展示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-30T09:19:01.589007Z",
     "start_time": "2021-04-30T09:19:01.468170Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "量子门的矩阵表达式为：\n",
      "[[ 6.123234e-17+0.j -6.123234e-17-1.j]\n",
      " [ 6.123234e-17-1.j  6.123234e-17+0.j]]\n"
     ]
    }
   ],
   "source": [
    "# 设置角度参数 theta = pi\n",
    "theta = np.array([np.pi])\n",
    "    \n",
    "# 我们需要将 Numpy array 转换成 Paddle 中的 Tensor\n",
    "theta = paddle.to_tensor(theta)\n",
    "\n",
    "# 设置计算所需的量子比特数量\n",
    "num_qubits = 1\n",
    "\n",
    "# 初始化我们的单比特量子电路\n",
    "cir = UAnsatz(num_qubits)\n",
    "\n",
    "# 在第一个量子比特(第0号量子比特)的位置上施加一个 Rx 旋转门， 角度为 pi\n",
    "which_qubit = 0\n",
    "cir.rx(theta, which_qubit)\n",
    "\n",
    "# 打印出这个量子门\n",
    "# 转换成 numpy \n",
    "print('量子门的矩阵表达式为：')\n",
    "print(cir.U.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "结果和 $X$（NOT）门只相差一个全局相位$-i$\n",
    "\n",
    "$$\n",
    "\\text{output} = \\begin{bmatrix} 0 &-i \\\\ -i &0 \\end{bmatrix}\n",
    "= -i\\begin{bmatrix} 0 &1 \\\\ 1 &0 \\end{bmatrix} = -i X.\n",
    "\\tag{17}\n",
    "$$\n",
    "\n",
    "有兴趣的话，你可以仔细思考一下为什么在量子计算中，全局相位并不重要。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习: 创建 $Y$ 门\n",
    "\n",
    "那么按照以上的例子依葫芦画瓢，你是否可以试着自己创建一个 $Y$ 门？试着补全下面的代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "theta = \"your code\"\n",
    "    \n",
    "theta = paddle.to_tensor(theta)\n",
    "num_qubits = 1\n",
    "cir = UAnsatz(\"your code\")\n",
    "cir.ry(\"your code\")\n",
    "print(cir.U.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "和原来一样，我们还是多了一个全局相位\n",
    "\n",
    "$$\n",
    "\\text{output} = \\begin{bmatrix} 0 &-1 \\\\ 1 &0 \\end{bmatrix}\n",
    "= -i\\begin{bmatrix} 0 &-i \\\\ i &0 \\end{bmatrix} = -i Y.\n",
    "\\tag{18}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>[回到 <a href=\"#Contents\">目录</a>]</p>\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <a name=\"VA\">量子电路模板/量子神经网络</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "经过上面的准备，你现在有一定的知识基础可以了解量子机器学习了。简单来说，我们要做的就是利用参数化量子电路（Parametrized Quantum Circuit, PQC）来替代传统的神经网络来完成机器学习的任务。处理的对象可以是经典数据也可以是量子数据。我们一般会准备一个可调节参数的量子电路（PQC），也被称作量子神经网络（Quantum Neural Network, QNN）或者电路模板（ansatz），里面的参数是人为可调节的（这些参数大多数情况下就是旋转门的角度 $\\theta$）。例如上一节中看到的用参数 $\\pi$ 构造 $X$ 门，这其实就是最简单的量子神经网络。如果再加上一个精心设计的损失函数，就可以将一个计算问题转化为寻找损失函数的最值问题。然后不断调节电路中的参数直到损失函数下降至收敛（此时损失函数达到最优值或次优值），我们就完成了优化。这样的一种在量子设备上估值损失函数然后在经典设备上进行优化的框架被称为量子-经典混合优化，或者变分量子算法（Variational Quantum Algorithms, VQA）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"QNN\">示例: 如何创建量子神经网络 QNN？</a>\n",
    "\n",
    "QNN 通常可以表示为一些单比特量子旋转门和双比特门的组合。其中一个可以高效利用硬件的架构是只包含 $\\{R_x, R_y, R_z, \\text{CNOT}\\}$ 这四种量子门的模板。它们很容易在 NISQ （Noisy-Intermidiate-Scale-Quantum）设备（通常是超导量子比特）上实现，因为 $\\text{CNOT}$ 只需要实施在相邻量子比特上。一个例子可见下图：\n",
    "\n",
    "\n",
    "![intro-fig-gate1](./figures/intro-fig-gate1.png)\n",
    "\n",
    "通常来说，每条线代表一个量子比特。我们把图最上端的认为是第一个量子比特 $q_0$，依次往下。从左到右代表我们施加门的时间顺序，先施加最左边的量子门。接下来，我们来看看如何在量桨上建造这个简单的两比特量子神经网络"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-30T09:19:07.433031Z",
     "start_time": "2021-04-30T09:19:07.409641Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "图中量子神经网络 U(theta=pi) 的矩阵表达式是:\n",
      "[[ 0.0000000e+00 -1.0000000e+00  6.1232340e-17 -6.1232340e-17]\n",
      " [-1.0000000e+00  0.0000000e+00 -6.1232340e-17  6.1232340e-17]\n",
      " [-6.1232340e-17  6.1232340e-17  1.0000000e+00  1.2246468e-16]\n",
      " [ 6.1232340e-17 -6.1232340e-17 -1.2246468e-16  1.0000000e+00]]\n"
     ]
    }
   ],
   "source": [
    "# 设置角度参数 theta \n",
    "theta = np.full([4], np.pi)\n",
    "    \n",
    "# 我们需要将 Numpy array 转换成 Paddle 中的 Tensor\n",
    "theta = paddle.to_tensor(theta)\n",
    "\n",
    "# 初始化量子电路\n",
    "num_qubits = 2\n",
    "cir = UAnsatz(num_qubits)\n",
    "\n",
    "# 添加单比特旋转门\n",
    "cir.ry(theta[0], 0)\n",
    "cir.ry(theta[1], 1)\n",
    "\n",
    "# 添加两比特门\n",
    "cir.cnot([0, 1])\n",
    "\n",
    "# 添加单比特旋转门\n",
    "cir.ry(theta[2], 0)\n",
    "cir.ry(theta[3], 1)\n",
    "\n",
    "print('图中量子神经网络 U(theta=pi) 的矩阵表达式是:')\n",
    "print(cir.U.numpy().real)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$$\n",
    "\\text{output} = \n",
    "\\begin{bmatrix} \n",
    "0  &-1 &0 &0 \\\\ \n",
    "-1 &0  &0 &0 \\\\\n",
    "0  &0  &1 &0 \\\\\n",
    "0  &0  &0 &1 \n",
    "\\end{bmatrix}.\n",
    "\\tag{19}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习\n",
    "\n",
    "给你如下代码，你能想象出对应的电路吗？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-04-30T09:19:17.518832Z",
     "start_time": "2021-04-30T09:19:17.507574Z"
    }
   },
   "outputs": [],
   "source": [
    "theta = np.full([6], np.pi)\n",
    "    \n",
    "theta = paddle.to_tensor(theta)\n",
    "\n",
    "num_qubits = 3\n",
    "cir = UAnsatz(num_qubits)  \n",
    "\n",
    "cir.ry(theta[0], 0)\n",
    "cir.ry(theta[1], 1)\n",
    "cir.ry(theta[2], 2)\n",
    "\n",
    "cir.cnot([0, 1])\n",
    "cir.cnot([1, 2])\n",
    "\n",
    "cir.ry(theta[3], 0)\n",
    "cir.ry(theta[4], 1)\n",
    "cir.ry(theta[5], 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "答案如下:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"figures/intro-fig-gate2.png\" width=\"450\" >\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "也可以使用量桨中打印电路的功能查看构造好的电路："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--Ry(3.1416)----*----Ry(3.1416)----------------\n",
      "                |                              \n",
      "--Ry(3.1416)----X---------*--------Ry(3.1416)--\n",
      "                          |                    \n",
      "--Ry(3.1416)--------------X--------Ry(3.1416)--\n",
      "                                               \n"
     ]
    }
   ],
   "source": [
    "print(cir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"Ansatz\">内置的电路模板</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在最新版本的 Paddle Quantum 中，我们提供了一些内置的电路模板方便场景部署。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:12.042782Z",
     "start_time": "2021-03-09T03:53:11.531307Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYgAAAEPCAYAAABY9lNGAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Z1A+gAAAACXBIWXMAAAsTAAALEwEAmpwYAAAZJElEQVR4nO3df5xddX3n8debn6JYfhmpkmhoidpQlGpEH+3WqijCY9VgBQ26FVwsdpVteai1cWtRqbuVVsW64tZ0URFXA0v9kS1RdEXrrhUkID8aIBL5GdQafiqyiJHP/nFOyM2dMzN3hty5l+T1fDzmMfee7zkz75k/5j3nfM+PVBWSJPXbadQBJEnjyYKQJHWyICRJnSwISVInC0KS1GmXUQfYVh73uMfVwoULRx1Dkh5RLrvsstural7X2HZTEAsXLmTNmjWjjiFJjyhJbp5szENMkqROFoQkqZMFI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Ody/BXyjHT4aGOQP/6DrSQ+Lk9TaISU5HHhXVT2vZ9mv0FwLsQA4Bliy+YltSf6R5nGu32j3IP6e5k6lPwKWVdXGJJ+kOTvlicD7gXXA7VX1gp7vsS9wHfDkqvp/Pct/u932nvbjlcALgZOA3YD1wB/Q3Omzfz2AM4F5wH3AH1bVddvkF6UdmnsQ2lEdDGz1mMyq+glwE831D1N5DLCmqg6muSPnu/q+zoeBH9DcovsFfWN30tyn6OYkn03y2iQ7tY+eXAX8aVUdWlXfBz5XVc9u9zSuBU6cZL0VNI/9fBbwNuCjM/5tSB28DkKauQeBc9vXn6Y5VDWwqnpDkkOAF9H8QX8xzd1P+/1mkvfS3JF3T+DC/hWS7An8NvA/m6NmAEw7jyINwoLQjuoamsNID2kPMf0qzaGh32TrPexHTfG1ZnyctqquBq5Ocg5wI90F8Ung6Kq6MskJwPM71tkJuLuqDp1pBmk6HmLSjuprwKOTvA4gyc40D1v6SDs3cBNwaJKdkiygucp6s53YUi6vAf5vx9f/KfDY/oVJ9kzy/J5Fh7LlHlD92zwW+GE7sf3arq/dHha7sX3KIWk8Y6ofXBqUBaEdUjVnZ7wCOKa9B9MdwINV9Z/bVb5F85/9NcCHgct7Nv8ZcFiSf6GZSD6t41usAL6c5Ot9ywO8Pcm6JFcA72HL3sNK4E/bU2B/HfgL4JI2S++kc/96rwVOTHIlsJbm2QzSw+ZZTBIPnUX0WeAVVXX5dOtLOwILQpLUyUNMkqROFoQkqZMFIUnqZEFIkjpZEJKkThaEJKnT/weRuZs3hsDuNQAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "N = 3  # 设置量子比特数\n",
    "   \n",
    "# 初始化量子电路\n",
    "cir = UAnsatz(N)\n",
    "\n",
    "# 给每一个量子比特施加哈达玛门 H\n",
    "cir.superposition_layer()\n",
    "\n",
    "# 制备输出态\n",
    "# 如果用户不输入初始量子态，默认初始为|00..0>\n",
    "final_state = cir.run_state_vector()\n",
    "\n",
    "# 获取概率分布的理论值，令 shots = 0\n",
    "res = cir.measure(shots = 0, plot = True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:12.698149Z",
     "start_time": "2021-03-09T03:53:12.187946Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAEPCAYAAABP1MOPAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Z1A+gAAAACXBIWXMAAAsTAAALEwEAmpwYAAAXIklEQVR4nO3dfbRddX3n8feHIGqF1gcitSQYqkGLT6gRXXWmRQsWlhawooZaFUfFjjKVZbUNU0VLnSlqdaxjbI31gbajEa3VtETR8aGd2kETEMUEIxGChNYaeVBbRzHynT/ODpycnHvvySX77Jvs92utu3L2/u1zzyf3j/u5e//2Q6oKSVJ/HdR1AElStywCSeo5i0CSes4ikKSeswgkqecO7jrA3jr88MNr2bJlXceQpP3K5Zdf/p2qWjxubL8rgmXLlrFx48auY0jSfiXJ9TONeWhIknrOIpCknrMIJKnnLAJJ6jmLQJJ6ziKQpJ6zCCSp5ywCSeo5i0CSem6/u7L4rli26pJOP3/bhU/t9PMlaRz3CCSp5ywCSeo5i0CSeq7VIkhycpItSbYmWTXDNs9KsjnJpiTvbzOPJGlPrU0WJ1kErAZOArYDG5Ksq6rNQ9ssB84DnlhVtyS5f1t5JEnjtblHcDywtaqurarbgLXAaSPbvBhYXVW3AFTVt1vMI0kao80iOBK4YWh5e7Nu2DHAMUk+n+SyJCeP+0ZJzk6yMcnGHTt2tBRXkvqp68nig4HlwAnAmcC7ktx7dKOqWlNVK6pqxeLFY5+0JkmapzaL4EZg6dDykmbdsO3Auqr6cVVdB3ydQTFIkqakzSLYACxP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k8F9ijCJLcDVgD/FrzjOZHA59rhk8HJvkFP+l20l3mZLEOWEl+BXhtVf3S0LqfZnAdwVLgDGDFrqd/Jfk7Bo8A/VyzR/AuBnfW/Bawsqp2JHkfg7NBfg74Y2AL8J2qetLQZ9wX+BrwwKr6f0Prf7F573ebr2cATwbOBg4BtgLPZXBnytHtAFYDi4EfAC+uqq/tkx+Ues89Ah3IHgbs9njFqvoesI3BtQOzuRewsaoexuAOkq8d+T5vA/6ZwW2jnzQydjOD+/Bcn+QDSZ6T5KDmkYXrgFdV1XFV9Q3gI1X1uGbP4WrghTNst4bB4yIfC7wSeMde/zSkGXgdgTTe7cAHm9d/xeAQ08Sq6kVJHgGcyOAX90kM7tY56uFJXs/g7rGHApeObpDkUOAXgQ8NjnYBMOc8hzQpi0AHss0MDv/coTk09LMMDuk8nN33iu8xy/fa62OoVXUVcFWSvwSuY3wRvA84vaq+nOQs4IQx2xwE3FpVx+1tBmkSHhrSgezTwE8leR5AkkUMHujz9ubY/TbguCQHJVnK4IrjXQ7izhL5DeAfx3z/7wOHja5McmiSE4ZWHced9zcafc9hwL80E8zPGfe9m8NZ1zVPzCMDj5rtPy7tDYtAB6wanAnxdOCM5v5CNwG3V9V/azb5PIO/1DcDbwOuGHr7vwPHJ/kqgwndC8Z8xBrgE0k+O7I+wO8m2ZLkSuAPuHNvYC3wqubU0gcBrwG+0GQZnvwd3e45wAuTfBnYxODZANI+4VlD6o3mrJ0PAE+vqivm2l7qC4tAknrOQ0OS1HMWgST1nEUgST1nEUhSz1kEktRzFoEk9dz/B9VMzjhMqx3WAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "N = 3  # 设置量子比特数\n",
    "    \n",
    "# 初始化量子电路\n",
    "cir = UAnsatz(N)\n",
    "\n",
    "# 给每一个量子比特施加 Ry(pi/4)旋转\n",
    "cir.weak_superposition_layer()\n",
    "\n",
    "# 制备输出态\n",
    "# 如果用户不输入初始量子态，默认初始为|00..0>\n",
    "final_state = cir.run_state_vector()\n",
    "\n",
    "# 获取概率分布的理论值，令 shots = 0\n",
    "res = cir.measure(shots = 0, plot = True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下是一个使用频率较高的电路模板 `complex_entangled_layer(theta, DEPTH)`，用户可按照电路深度参数 `DEPTH` 快速拓展电路。其中涉及的广义旋转门 $U_3$ 的定义为\n",
    "\n",
    "$$\n",
    "U_3(\\theta, \\phi, \\varphi) := \n",
    "\\begin{bmatrix} \n",
    "\\cos \\frac{\\theta}{2} & -e^{i \\varphi}\\sin \\frac{\\theta}{2} \\\\ \n",
    "e^{i \\phi}\\sin \\frac{\\theta}{2} &e^{i (\\phi+\\varphi)} \\cos \\frac{\\theta}{2} \n",
    "\\end{bmatrix},\\tag{20}\n",
    "$$\n",
    "\n",
    "$U_3$ 旋转门在效果上是等价于以下组合旋转门的：\n",
    "\n",
    "$$\n",
    "U_3(\\theta, \\phi, \\varphi) \n",
    "= R_z(\\phi)*R_y(\\theta)*R_z(\\varphi)\n",
    ":=\n",
    "\\begin{bmatrix}\n",
    "e^{-i\\frac{\\phi}{2}} & 0 \\\\ \n",
    "0 & e^{i\\frac{\\phi}{2}}\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    "\\cos \\frac{\\theta}{2} &-\\sin \\frac{\\theta}{2} \\\\ \n",
    "\\sin \\frac{\\theta}{2} &\\cos \\frac{\\theta}{2} \n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    "e^{-i\\frac{\\varphi}{2}} & 0 \\\\ \n",
    "0 & e^{i\\frac{\\varphi}{2}}\n",
    "\\end{bmatrix}.\\tag{21}\n",
    "$$\n",
    "\n",
    "感兴趣的读者不妨自行验证一下。\n",
    "\n",
    "<img src=\"figures/intro-fig-complex_entangled_layer2-cn.png\" width=\"850\" >\n",
    "\n",
    "特别地，当我们处理的任务不涉及虚数时，使用电路模板 `real_entangled_layer(theta, DEPTH)` 会更加高效（$R_y$ 旋转门替代 $U_3$）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:14.040033Z",
     "start_time": "2021-03-09T03:53:13.566616Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAY4AAAEPCAYAAABV6CMBAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Z1A+gAAAACXBIWXMAAAsTAAALEwEAmpwYAAAfDklEQVR4nO3de5gdVZ3u8e9LgICK3FVMwESJF5AxSkDOOHIUReFRIWqQQBRw0OgoozxexnBU1KhzYBxvCKhxuKoQEG85EkBHxHNGBdPBCCQYaSFAImi4owxo5D1/VDXs7OzeXdXp6r0h7+d59tO116pa+7f7j/51rbVqLdkmIiKiqs16HUBERDy2JHFEREQtSRwREVFLEkdERNSSxBEREbVs3usAxsNOO+3kKVOm9DqMiIjHlKVLl95he+f28k0icUyZMoWBgYFehxER8Zgi6eZO5emqioiIWpI4IiKiliSOiIioJYkjIiJqSeKIiIhakjgiIqKWJI6IiKgliSMiImpJ4oiIiFo2iSfHN8aUeRf37LNXnfSann12RMRwcscRERG1NJo4JB0kaaWkQUnzOtTvL+lqSeskzWopf7mkZS2vByXNLOvOlnRTS930Jr9DRESsr7GuKkkTgNOAA4HVwBJJi2yvaDntFuAY4AOt19r+CTC9bGcHYBD4YcspH7R9UVOxR0TE8Joc49gXGLR9I4CkhcChwCOJw/aqsu7hLu3MAi6x/UBzoUZERFVNdlVNAm5teb+6LKtrNnB+W9mnJV0j6fOSJna6SNJcSQOSBtauXTuKj42IiE76enBc0i7AXsBlLcUnAM8F9gF2AD7U6VrbC2zPsD1j55032IckIiJGqcnEsQbYteX95LKsjjc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d4YERsts6oiuihnNZ0PvN721SOdH7EpSOKIiIha0lUVERG1JHFEREQtSRwREVFLEkdERNSSxBEREbUkcURERC3/HzkY2quZCVjYAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "N = 4            # 设置量子比特数\n",
    "DEPTH = 6        # 设置量子电路深度\n",
    "theta = np.random.randn(DEPTH, N, 3)\n",
    "    \n",
    "# 我们需要将 Numpy array 转换成 Paddle 中的 Tensor\n",
    "theta = paddle.to_tensor(theta)\n",
    "\n",
    "# 初始化量子电路\n",
    "cir = UAnsatz(N)\n",
    "\n",
    "# 添加深度为 D = 6 的复数强纠缠结构QNN {Rz+Ry+Rz/U3 + CNOT's}\n",
    "cir.complex_entangled_layer(theta, DEPTH)\n",
    "\n",
    "# 制备输出态\n",
    "# 如果用户不输入初始量子态，默认初始为|00..0>\n",
    "final_state = cir.run_state_vector()\n",
    "\n",
    "# 测量输出态的[0，1，2]号量子比特2048次，统计测量结果的频率\n",
    "res = cir.measure(shots = 2048, which_qubits = [0, 1, 2], plot = True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>[回到 <a href=\"#Contents\">目录</a>]</p>\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <a name=\"Mode\"> 量桨的运行模式说明</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  <a name=\"vec\"> 波函数向量模式 </a>\n",
    "\n",
    "所谓的波函数模式也就是用复数向量表示和储存量子态。向量模式只能处理纯态，但这种模式在家用电脑硬件高效支持 **20+ 量子比特**的运算。用户可以测试下自己电脑的极限在哪里。在这种表示下，量子门（酉矩阵）作用在量子比特（一个复向量表示其所处状态）上本质上的运算是**矩阵乘以向量**：\n",
    "\n",
    "$$\n",
    "\\lvert {\\psi}\\rangle = U \\lvert {\\psi_0}\\rangle. \\tag{22}\n",
    "$$\n",
    "\n",
    "代码中，具体体现在 UAnsatz的调用 `cir.run_state_vector(input_state = None)`。如果我们不输入任何初始量子态，就会默认所有的量子比特都处于 $\\lvert {0}\\rangle$ 态。接着来看个具体的例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:27.327236Z",
     "start_time": "2021-03-09T03:53:15.824502Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 9.65721758e-05+0.j -4.38538841e-04+0.j  2.68195580e-05+0.j ...\n",
      "  -4.32163794e-04+0.j -6.48040560e-05+0.j  1.52848347e-04+0.j]]\n"
     ]
    }
   ],
   "source": [
    "from paddle_quantum.state import vec, vec_random\n",
    "\n",
    "N = 20           # 设置量子比特数\n",
    "DEPTH = 6        # 设置量子电路深度\n",
    "theta = np.random.randn(DEPTH, N, 1)\n",
    "\n",
    "# 调用内置的 |00..0> 初始态\n",
    "initial_state1 = vec(N)\n",
    "# 调用内置的随机量子态 |psi>\n",
    "initial_state2 = vec_random(N)\n",
    "    \n",
    "# 我们需要将 Numpy array 转换成 Paddle 中的 Tensor\n",
    "theta = paddle.to_tensor(theta)\n",
    "initial_state = paddle.to_tensor(initial_state1)\n",
    "\n",
    "# 初始化量子电路\n",
    "cir = UAnsatz(N)\n",
    "\n",
    "# 添加深度为 Depth 的实数强纠缠结构QNN {Ry+CNOT's}\n",
    "cir.real_entangled_layer(theta, DEPTH)\n",
    "\n",
    "# 制备输出态\n",
    "# 如果用户不输入初始量子态，默认初始为|00..0>\n",
    "final_state = cir.run_state_vector(initial_state)\n",
    "print(final_state.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  <a name=\"density\"> 密度矩阵模式 </a>\n",
    "\n",
    "同时 Paddle quantum也支持了密度矩阵运算模式，也就是用一个密度矩阵 $\\rho = \\sum_i P_i \\lvert {\\psi_i}\\rangle\\langle{\\psi_i} \\lvert$ 表示和储存量子态。该模式下可以根据算法需要支持**混合态模拟**。但是在密度矩阵模式下，家用电脑硬件只能运行10个左右的量子比特。请用户注意这方面的限制，我们也在不断优化这个模式下的模拟器性能。在这种表示下，量子门 (酉矩阵)作用在量子态(一个迹为1的厄尔米特矩阵)上本质上的运算是**矩阵乘法**：\n",
    "\n",
    "$$\n",
    "\\rho = U \\rho_0 U^\\dagger. \\tag{23}\n",
    "$$\n",
    "\n",
    "代码中，具体体现在 UAnsatz的调用 `cir.run_density_matrix()`。接着来看个具体的例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:27.433188Z",
     "start_time": "2021-03-09T03:53:27.333861Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.56503575+0.j  0.44320439+0.j -0.13063786+0.j  0.17964958+0.j]\n",
      " [ 0.44320439+0.j  0.34764194+0.j -0.10247011+0.j  0.14091406+0.j]\n",
      " [-0.13063786+0.j -0.10247011+0.j  0.03020384+0.j -0.04153549+0.j]\n",
      " [ 0.17964958+0.j  0.14091406+0.j -0.04153549+0.j  0.05711846+0.j]]\n"
     ]
    }
   ],
   "source": [
    "from paddle_quantum.state import density_op, density_op_random, completely_mixed_computational\n",
    "\n",
    "N = 2            # 设置量子比特数\n",
    "DEPTH = 6        # 设置量子电路深度\n",
    "theta = np.random.randn(DEPTH, N, 1)\n",
    "\n",
    "# 调用内置的 |00..0><00..0| 初始态\n",
    "initial_state1 = density_op(N)\n",
    "# 调用内置的随机量子态, 可以指定是否允许复数元素和矩阵秩 \n",
    "initial_state2 = density_op_random(N, real_or_complex=2, rank=4)\n",
    "# 调用内置的计算基下的完全混合态 \n",
    "initial_state3 = completely_mixed_computational(N)\n",
    "    \n",
    "# 我们需要将 Numpy array 转换成 Paddle 中的 Tensor\n",
    "theta = paddle.to_tensor(theta)\n",
    "initial_state = paddle.to_tensor(initial_state1)\n",
    "\n",
    "# 初始化量子电路\n",
    "cir = UAnsatz(N)\n",
    "\n",
    "# 添加深度为 Depth 的实数强纠缠结构QNN {Ry+CNOT's}\n",
    "cir.real_entangled_layer(theta, DEPTH)\n",
    "\n",
    "# 制备输出态\n",
    "# 如果用户不输入初始量子态，默认初始为|00..0><00..0|\n",
    "final_state = cir.run_density_matrix(initial_state)\n",
    "print(final_state.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  <a name=\"Bell\">练习：如何从计算基制备贝尔态</a>\n",
    "\n",
    "贝尔态是一种很常用的量子纠缠态，可以表示为\n",
    "\n",
    "$$\n",
    "\\lvert {\\Phi^+}\\rangle = \\frac{1}{\\sqrt{2}} \\big(\\lvert {00}\\rangle + \\lvert {11}\\rangle\\big)\n",
    "= \\frac{1}{\\sqrt{2}} \\,\n",
    "\\begin{bmatrix}\n",
    "1 \\\\\n",
    "0 \\\\\n",
    "0 \\\\\n",
    "1\n",
    "\\end{bmatrix}.\\tag{24}\n",
    "$$\n",
    "\n",
    "那么我们如何用量桨来制备一个贝尔态呢？只需要如下的量子电路："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"figures/intro-fig-bell2.png\" width=\"750\" >"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:27.924758Z",
     "start_time": "2021-03-09T03:53:27.452981Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAEJCAYAAACZjSCSAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/Z1A+gAAAACXBIWXMAAAsTAAALEwEAmpwYAAAVy0lEQVR4nO3dfbRddX3n8fcn4VFBBUGlBAytYSxaQ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Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我们制备出的贝尔态是:\n",
      "[0.70710678+0.j 0.        +0.j 0.        +0.j 0.70710678+0.j]\n"
     ]
    }
   ],
   "source": [
    "# 初始化量子电路\n",
    "cir = UAnsatz(2)\n",
    "\n",
    "# 添加量子门\n",
    "cir.h(0)\n",
    "cir.cnot([0, 1])  \n",
    "\n",
    "# 制备输出态\n",
    "# 如果用户不输入初始量子态，默认初始为|00..0>\n",
    "output_state = cir.run_state_vector()\n",
    "\n",
    "# 我们测量输出态2048次，获得测量结果频率分布\n",
    "# 如果用户想获取概率分布的理论值，可以令 shots = 0\n",
    "cir.measure(shots = 2048, plot = True)\n",
    "\n",
    "print('我们制备出的贝尔态是:')\n",
    "print(output_state.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>[回到 <a href=\"#Contents\">目录</a>]</p>\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <a name=\"Op\"> 飞桨 Paddlepaddle 优化器使用教程</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"GD\"> 示例: 利用飞桨的梯度下降来优化多元函数</a>\n",
    "\n",
    "\n",
    "在这一节，我们学习如何用飞桨中的优化器找到一个多元函数的极小值\n",
    "\n",
    "$$\n",
    "\\mathcal{L}(\\theta_1, \\theta_2, \\theta_3)\n",
    "= (\\theta_1)^2 + (\\theta_2)^2 + (\\theta_3)^2 + 10. \\tag{25}\n",
    "$$\n",
    "\n",
    "可以看出，只有当 $\\theta_1 = \\theta_2 = \\theta_3 = 0$ 的时候，$\\mathcal{L}$ 取最小值 $10$。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:47.622260Z",
     "start_time": "2021-03-09T03:53:47.183431Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "损失函数的最小值是:  10.000000010745854\n"
     ]
    }
   ],
   "source": [
    "# 超参数设置\n",
    "theta_size = 3 \n",
    "ITR = 200       # 设置迭代次数\n",
    "LR = 0.5        # 设置学习速率\n",
    "SEED = 1        # 固定随机数种子\n",
    "paddle.seed(SEED)\n",
    "\n",
    "class Optimization_ex1(paddle.nn.Layer):\n",
    "    \n",
    "    def __init__(self, shape, dtype='float64'):\n",
    "        super(Optimization_ex1, self).__init__()\n",
    "        \n",
    "        # 初始化一个长度为 theta_size的可学习参数列表，并用 [-5, 5] 的均匀分布来填充初始值\n",
    "        self.theta = self.create_parameter(shape=shape, \n",
    "                                           default_initializer=paddle.nn.initializer.Uniform(low=-5., high=5.), \n",
    "                                           dtype=dtype, is_bias=False)\n",
    "\n",
    "    # 定义损失函数和前向传播机制\n",
    "    def forward(self):\n",
    "        loss = self.theta[0] ** 2 +  self.theta[1] ** 2 + self.theta[2] ** 2 + 10\n",
    "        return loss\n",
    "    \n",
    "# 记录中间优化结果\n",
    "loss_list = []\n",
    "parameter_list = []\n",
    "    \n",
    "# 定义网络维度\n",
    "myLayer = Optimization_ex1([theta_size])\n",
    "\n",
    "# 一般来说，我们利用Adam优化器来获得相对好的收敛，当然你可以改成SGD或者是RMSprop.\n",
    "opt = paddle.optimizer.Adam(learning_rate = LR, parameters = myLayer.parameters())    \n",
    "\n",
    "# 优化循环\n",
    "for itr in range(ITR):\n",
    "\n",
    "    # 向前传播计算损失函数\n",
    "    loss = myLayer()[0]\n",
    "\n",
    "    # 反向传播优化损失函数\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # 记录学习曲线\n",
    "    loss_list.append(loss.numpy()[0])\n",
    "    parameter_list.append(myLayer.parameters()[0].numpy())\n",
    "\n",
    "print('损失函数的最小值是: ', loss_list[-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"ex2\"> 练习: 本征值寻找</a>\n",
    "\n",
    "接下来，我们试一个更复杂的损失函数。首先我们介绍一个随机的埃尔米特矩阵 $H$，其**本征值**为矩阵 $D$ 的对角元素， \n",
    "\n",
    "$$\n",
    "D = \\begin{bmatrix} 0.2 &0 \\\\ 0 &0.8 \\end{bmatrix}, \\tag{26}\n",
    "$$\n",
    "\n",
    "不用担心，我们会帮你生成这个埃尔米特矩阵 $H$。\n",
    "\n",
    "然后我们初始化参数向量$\\boldsymbol{\\theta}$，构造出一个简单的线性运算 $U(\\boldsymbol{\\theta}) = R_z(\\theta_1)*R_y(\\theta_2)*R_z(\\theta_3)$：\n",
    "\n",
    "$$\n",
    "U(\\theta_1, \\theta_2, \\theta_3) = \n",
    "\\begin{bmatrix}\n",
    "e^{-i\\frac{\\theta_1}{2}} & 0 \\\\ \n",
    "0 & e^{i\\frac{\\theta_1}{2}}\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    "\\cos \\frac{\\theta_2}{2} &-\\sin \\frac{\\theta_2}{2} \\\\ \n",
    "\\sin \\frac{\\theta_2}{2} &\\cos \\frac{\\theta_2}{2} \n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    "e^{-i\\frac{\\theta_3}{2}} & 0 \\\\ \n",
    "0 & e^{i\\frac{\\theta_3}{2}}\n",
    "\\end{bmatrix}, \\tag{27}\n",
    "$$\n",
    "\n",
    "我们让这个矩阵（模板）乘以 $\\lvert {0}\\rangle$，得到一个新的 2 维复向量\n",
    "\n",
    "$$ \n",
    "\\lvert {\\phi}\\rangle = U(\\theta_1, \\theta_2, \\theta_3)\\lvert {0}\\rangle, \\tag{28}\n",
    "$$\n",
    "\n",
    "然后，我们定义损失函数为\n",
    "\n",
    "$$\n",
    "\\mathcal{L}(\\theta_1, \\theta_2, \\theta_3) \n",
    "= \\langle{\\phi} \\lvert H \\lvert {\\phi}\\rangle \n",
    "=  \\langle{0} \\lvert  U^{\\dagger}H U \\lvert {0}\\rangle. \\tag{29}\n",
    "$$\n",
    "\n",
    "来看看优化后我们得到了什么！"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:50.904606Z",
     "start_time": "2021-03-09T03:53:50.248060Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "随机生成的矩阵 H 是:\n",
      "[[0.65531213+0.00000000e+00j 0.00378707+2.56639434e-01j]\n",
      " [0.00378707-2.56639434e-01j 0.34468787+1.21430643e-17j]] \n",
      "\n",
      "不出所料，H 的本征值是:\n",
      "[0.2 0.8]\n"
     ]
    }
   ],
   "source": [
    "from scipy.stats import unitary_group\n",
    "\n",
    "# V 是一个 2x2 的随机酉矩阵\n",
    "V = unitary_group.rvs(2)\n",
    "\n",
    "# D 的对角元是H的本征值\n",
    "# 你可以任意改变这里的对角元数值\n",
    "D = np.diag([0.2, 0.8])\n",
    "\n",
    "# V_dagger 是 V 的埃尔米特转置\n",
    "V_dagger = V.conj().T\n",
    "\n",
    "# @：代表矩阵乘积运算\n",
    "H = (V @ D @ V_dagger)\n",
    "print('随机生成的矩阵 H 是:')\n",
    "print(H, '\\n')\n",
    "print('不出所料，H 的本征值是:')\n",
    "print(np.linalg.eigh(H)[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:50.916504Z",
     "start_time": "2021-03-09T03:53:50.908516Z"
    }
   },
   "outputs": [],
   "source": [
    "# 超参数设置\n",
    "theta_size = 3    # 设置 theta 维度\n",
    "num_qubits = 1    # 设置量子比特数\n",
    "ITR = 50          # 设置迭代次数\n",
    "LR = 0.5          # 设置学习速率\n",
    "SEED = 1          # 固定theta参数的随机数种子\n",
    "paddle.seed(SEED)\n",
    "\n",
    "# 单独设置电路模块\n",
    "def U_theta(theta):\n",
    "    \n",
    "    # 初始化电路然后添加量子门\n",
    "    cir = UAnsatz(num_qubits)\n",
    "    cir.rz(theta[0], 0)\n",
    "    cir.ry(theta[1], 0)\n",
    "    cir.rz(theta[2], 0)\n",
    "    \n",
    "    # 返回参数化矩阵\n",
    "    return cir.U"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:54.556150Z",
     "start_time": "2021-03-09T03:53:54.489747Z"
    }
   },
   "outputs": [],
   "source": [
    "class Optimization_ex2(paddle.nn.Layer):\n",
    "    \n",
    "    def __init__(self, shape, dtype='float64'):\n",
    "        super(Optimization_ex2, self).__init__()\n",
    "        \n",
    "        # 初始化一个长度为 theta_size的可学习参数列表，并用 [0, 2*pi] 的均匀分布来填充初始值\n",
    "        self.theta = self.create_parameter(shape=shape, \n",
    "                                           default_initializer=paddle.nn.initializer.Uniform(low=0., high=2*np.pi), \n",
    "                                           dtype=dtype, is_bias=False)\n",
    "        self.H = paddle.to_tensor(H)\n",
    "        \n",
    "    # 定义损失函数和前向传播机制\n",
    "    def forward(self):\n",
    "        \n",
    "        # 获取量子神经网络的酉矩阵表示\n",
    "        U = U_theta(self.theta)\n",
    "        \n",
    "        # 埃尔米特转置运算\n",
    "        U_dagger = dagger(U)\n",
    "        \n",
    "        # 计算损失函数函数\n",
    "        loss = paddle.real(matmul(U_dagger, matmul(self.H, U)))[0][0]\n",
    "        \n",
    "        return loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:53:59.114893Z",
     "start_time": "2021-03-09T03:53:58.381044Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "iter: 0   loss: 0.2878\n",
      "iter: 5   loss: 0.2202\n",
      "iter: 10   loss: 0.2044\n",
      "iter: 15   loss: 0.2010\n",
      "iter: 20   loss: 0.2003\n",
      "iter: 25   loss: 0.2001\n",
      "iter: 30   loss: 0.2000\n",
      "iter: 35   loss: 0.2000\n",
      "iter: 40   loss: 0.2000\n",
      "iter: 45   loss: 0.2000\n",
      "损失函数的最小值是:  0.2000001964593201\n"
     ]
    }
   ],
   "source": [
    "loss_list = []\n",
    "parameter_list = []\n",
    "    \n",
    "myLayer = Optimization_ex2([theta_size])\n",
    "\n",
    "# 这里采用 SGD 优化器\n",
    "opt = paddle.optimizer.SGD(learning_rate = LR, parameters = myLayer.parameters())    \n",
    "\n",
    "# 优化循环\n",
    "for itr in range(ITR):\n",
    "\n",
    "    # 前向传播计算损失函数\n",
    "    loss = myLayer()[0]\n",
    "\n",
    "    # 反向传播极小化损失函数\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # 记录学习曲线\n",
    "    loss_list.append(loss.numpy()[0])\n",
    "    parameter_list.append(myLayer.parameters()[0].numpy())\n",
    "    if itr % 5 == 0:\n",
    "        print('iter:', itr, '  loss: %.4f' % loss.numpy())\n",
    "\n",
    "print('损失函数的最小值是: ', loss_list[-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们可以改变一下 $H$ 的本征值。如果将它对角化后的的对角矩阵改变为\n",
    "\n",
    "$$\n",
    "D = \\begin{bmatrix} 0.8 &0 \\\\ 0 &1.2 \\end{bmatrix}, \\tag{30}\n",
    "$$\n",
    "\n",
    "你会发现我们仍然得到了 $H$ 的最小本征值 $0.8$。你能找到背后的原因吗？还是说这背后隐藏着什么理论？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>[回到 <a href=\"#Contents\">目录</a>]</p>\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <a name=\"demo\">量子机器学习案例</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <a name=\"VQE\"> 变分量子本征求解器——无监督学习</a>\n",
    "\n",
    "目前阶段，大规模的可容错的量子计算机还未实现。我们目前只能造出有噪音的，中等规模量子计算系统（NISQ）。现在一个利用 NISQ 的量子设备很有前景的算法种类就是量子-经典混合算法。人们期望这套方法也许可以在某些应用中超越经典计算机的表现。变分量子本征求解器（Variational Quantum Eigensolver, VQE）就是里面的一个重要应用。它利用参数化的电路搜寻广阔的希尔伯特空间，并利用经典机器学习中的梯度下降来找到最优参数，并接近一个哈密顿量的基态（也就是找到一个埃尔米特矩阵的最小本征值）。为了确保你能理解, 我们来一起过一遍以下两量子比特 (2-qubit)的例子。\n",
    "\n",
    "假设我们想找到如下哈密顿量的基态：\n",
    "\n",
    "$$\n",
    "H = 0.4 \\, Z \\otimes I + 0.4 \\, I \\otimes Z + 0.2 \\, X \\otimes X. \\tag{31}\n",
    "$$\n",
    "\n",
    "给定一种常见的量子神经网络架构"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"figures/intro-fig-vqeAnsatz.png\" width=\"450\" >"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们已经学会如何建造这个电路了。如果需要复习，请转到 <a href=\"#QNN\">这里</a>。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:54:03.717323Z",
     "start_time": "2021-03-09T03:54:03.709869Z"
    }
   },
   "outputs": [],
   "source": [
    "from paddle_quantum.utils import pauli_str_to_matrix\n",
    "\n",
    "# 首先生成泡利字符串表示下的哈密顿量\n",
    "# 相当于0.4*kron(I, Z) + 0.4*kron(Z, I) + 0.2*kron(X, X)\n",
    "# 其中， X，Y, Z是泡利矩阵， I是单位矩阵\n",
    "H_info = [[0.4, 'z0'], [0.4, 'z1'], [0.2, 'x0,x1']]\n",
    "\n",
    "# 超参数设置\n",
    "num_qubits = 2\n",
    "theta_size = 4\n",
    "ITR = 60\n",
    "LR = 0.4\n",
    "SEED = 999       \n",
    "\n",
    "# 把记录的关于哈密顿量的信息转化为矩阵表示\n",
    "H_matrix = pauli_str_to_matrix(H_info, num_qubits)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:54:04.655091Z",
     "start_time": "2021-03-09T03:54:04.643511Z"
    }
   },
   "outputs": [],
   "source": [
    "class vqe_demo(paddle.nn.Layer):\n",
    "    \n",
    "    def __init__(self, shape, dtype='float64'):\n",
    "        super(vqe_demo, self).__init__()\n",
    "        \n",
    "        # 初始化一个长度为theta_size的可学习参数列表，并用[0, 2*pi]的均匀分布来填充初始值\n",
    "        self.theta = self.create_parameter(shape=shape, \n",
    "                                           default_initializer=paddle.nn.initializer.Uniform(low=0., high=2*np.pi), \n",
    "                                           dtype=dtype, is_bias=False)\n",
    "        \n",
    "    # 定义损失函数和前向传播机制\n",
    "    def forward(self):\n",
    "        \n",
    "        # 初始量子电路\n",
    "        cir = UAnsatz(num_qubits)\n",
    "        \n",
    "        # 添加量子门\n",
    "        cir.ry(self.theta[0], 0)\n",
    "        cir.ry(self.theta[1], 1)\n",
    "        cir.cnot([0, 1])\n",
    "        cir.ry(self.theta[2], 0)\n",
    "        cir.ry(self.theta[3], 1)\n",
    "        \n",
    "        # 选择用量子态的向量表示\n",
    "        cir.run_state_vector()\n",
    "        \n",
    "        # 计算当前量子态下关于观测量H_info的期望值\n",
    "        # 也就是 <psi|H|psi>\n",
    "        loss = cir.expecval(H_info)\n",
    "        \n",
    "        return loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T03:54:17.622644Z",
     "start_time": "2021-03-09T03:54:08.611202Z"
    },
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "colab_type": "code",
    "id": "S9fO_sGR64LV",
    "outputId": "f1be9cac-5d5e-4944-c13d-32983628fa6c"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "iter: 0   loss: 0.7363\n",
      "iter: 10   loss: -0.5727\n",
      "iter: 20   loss: -0.7474\n",
      "iter: 30   loss: -0.8101\n",
      "iter: 40   loss: -0.8154\n",
      "iter: 50   loss: -0.8225\n",
      "计算得到的基态能量是:  -0.8242290080502013\n",
      "真实的基态能量为:  -0.8246211251235321\n"
     ]
    }
   ],
   "source": [
    "loss_list = []\n",
    "parameter_list = []\n",
    "\n",
    "# 定义网络维度\n",
    "vqe = vqe_demo([theta_size])\n",
    "\n",
    "# 一般来说，我们利用Adam优化器来获得相对好的收敛，当然你可以改成SGD或者是RMS prop.\n",
    "opt = paddle.optimizer.Adam(learning_rate = LR, parameters = vqe.parameters())    \n",
    "\n",
    "# 优化循环\n",
    "for itr in range(ITR):\n",
    "\n",
    "    # 前向传播计算损失函数\n",
    "    loss = vqe()\n",
    "\n",
    "    # 反向传播极小化损失函数\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # 记录学习曲线\n",
    "    loss_list.append(loss.numpy()[0])\n",
    "    parameter_list.append(vqe.parameters()[0].numpy())\n",
    "    if itr % 10 == 0:\n",
    "        print('iter:', itr, '  loss: %.4f' % loss.numpy())\n",
    "\n",
    "\n",
    "print('计算得到的基态能量是: ', loss_list[-1])\n",
    "print('真实的基态能量为: ', np.linalg.eigh(H_matrix)[0][0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>[回到 <a href=\"#Contents\">目录</a>]</p>\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <a name=\"References\">参考文献</a>\n",
    "\n",
    "[1] Nielsen, M. A. & Chuang, I. L. Quantum computation and quantum information. (Cambridge university press, 2010).\n",
    "\n",
    "[2] Phillip Kaye, Laflamme, R. & Mosca, M. An Introduction to Quantum Computing. (2007).\n",
    "\n",
    "[3] Biamonte, J. et al. Quantum machine learning. [Nature 549, 195–202 (2017).](https://www.nature.com/articles/nature23474)\n",
    "\n",
    "[4] Schuld, M., Sinayskiy, I. & Petruccione, F. An introduction to quantum machine learning. [Contemp. Phys. 56, 172–185 (2015).](https://www.tandfonline.com/doi/abs/10.1080/00107514.2014.964942)\n",
    "\n",
    "[5] Benedetti, M., Lloyd, E., Sack, S. & Fiorentini, M. Parameterized quantum circuits as machine learning models. [Quantum Sci. Technol. 4, 043001 (2019).](https://iopscience.iop.org/article/10.1088/2058-9565/ab4eb5)\n",
    "\n",
    "[6] [Peruzzo, A. et al. A variational eigenvalue solver on a photonic quantum processor. Nat. Commun. 5, 4213 (2014).](https://www.nature.com/articles/ncomms5213)\n",
    "\n",
    "[7] [McClean, J. R., Romero, J., Babbush, R. & Aspuru-Guzik, A. The theory of variational hybrid quantum-classical algorithms. New J. Phys. 18, 023023 (2016).](https://iopscience.iop.org/article/10.1088/1367-2630/18/2/023023)\n",
    "\n",
    "[8] [Kandala, A. et al. Hardware-efficient variational quantum eigensolver for small molecules and quantum magnets. Nature 549, 242–246 (2017).](https://www.nature.com/articles/nature23879)\n",
    "\n",
    "[9] [Mitarai, K., Negoro, M., Kitagawa, M. & Fujii, K. Quantum circuit learning. Phys. Rev. A 98, 032309 (2018).](https://journals.aps.org/pra/abstract/10.1103/PhysRevA.98.032309)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>[回到 <a href=\"#Contents\">目录</a>]</p>\n",
    "\n",
    "<hr>"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "QSD-Paddle.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "426.667px"
   },
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
